package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Project: reggie_order_out
 * @Author: 29292
 * @Create: 2022-05-18 10:33
 * @Desc：
 **/
@Slf4j
@WebFilter(filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    //创建存储未登录就放行资源
    private String []authUri = {
            "/backend/**",
            "/front/**",
            "/employee/login",
            "/employee/logout"
    };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String uri = request.getRequestURI();
        boolean isAuth = checkUri(uri);
        log.info("url:{}",uri);
        //判断是否为可放行资源
        if (isAuth){
            log.info("【可放行资源】");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //判断是否登录
        if (request.getSession().getAttribute("employeeId") != null){
            log.info("[确认登录正常放行]");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String errorLogin = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(errorLogin);
    }

    private boolean checkUri(String uri) {

        //匹配路径
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String s : authUri) {
            if (pathMatcher.match(s, uri)){
                return true;
            }
        }
        return false;
    }
}
